package com.example.sunsg.okhttptest.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Parcelable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.breadtrip.R;
import com.example.sunsg.okhttptest.adapter.ImagePreviewAdapter;
import com.example.sunsg.okhttptest.bean.OnViewTapListener;
import com.example.sunsg.okhttptest.bean.PreviewImage;
import com.example.sunsg.okhttptest.customview.PhotoDraweeView;

import java.util.ArrayList;
import java.util.List;

/**
 * 图片预览activity
 */

public class ImagePreviewActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener,OnViewTapListener{
    /**图片的路径*/
    public static final String KEY_PATHS = "key_paths";
    public static final String KEY_CURRENT_IMAGE_INDEX = "key_current_image_index";
    private List<PreviewImage> mImageList;
    private int mCurrentIndex;

    private TextView mTvTtitle;
    private ImageView mIvCheck;
    private TextView mTvFinish;
    private RelativeLayout mRlFooter;


    public ImagePreviewAdapter mImagePreviewAdapter;
    private ViewPager mVp;
    private int mTotalSize;
    private Toolbar toolbar;
    private AppBarLayout mAppBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_preview);
        parseIntent();
        initView();
        bindEvent();
    }

    /***
     * 解析 intent
     */
    private void parseIntent(){
        Intent intent = getIntent();
        if(intent != null){
            if(intent.hasExtra(KEY_PATHS)){
                mImageList = intent.getParcelableArrayListExtra(KEY_PATHS);
                mTotalSize = mImageList.size();
            }

            if(intent.hasExtra(KEY_CURRENT_IMAGE_INDEX)){
                mCurrentIndex = intent.getIntExtra(KEY_CURRENT_IMAGE_INDEX,0);
            }
        }
    }

    private void initView(){
        mAppBar = (AppBarLayout) findViewById(R.id.appbar);
        toolBar();
        mRlFooter = (RelativeLayout) findViewById(R.id.lay_image_footer);
        mTvTtitle = (TextView) findViewById(R.id.tv_title);
        mIvCheck = (ImageView) findViewById(R.id.im_check);
        mTvFinish = (TextView) findViewById(R.id.tv_iamge_finish);

        mVp = (ViewPager) findViewById(R.id.vp_image_pager);
        mImagePreviewAdapter = new ImagePreviewAdapter(getApplicationContext());
        mVp.setAdapter(mImagePreviewAdapter);
        notifyDataSetChange();
        setTitle();
        setChecked(false);
        setFinishCount();
        setOnTap(mCurrentIndex);
    }

    private void toolBar(){
        //设置toolbar
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //设置actionbar
        final ActionBar ab = getSupportActionBar();
//        ab.setTitle(""); //设置标题
//        ab.setSubtitle("");//设置副标题

        //设置左上角图片
        ab.setHomeAsUpIndicator(R.drawable.im_back);
        /**使左上角图片可见*/
        ab.setDisplayHomeAsUpEnabled(true);
    }

    /**
     * 刷新数据
     */
    private void notifyDataSetChange(){
        mImagePreviewAdapter.clear();
        mImagePreviewAdapter.addAll(mImageList);
        mImagePreviewAdapter.notifyDataSetChanged();

        onItemChange(mCurrentIndex);
    }

    private void bindEvent(){
        mVp.setCurrentItem(mCurrentIndex);
        mVp.addOnPageChangeListener(this);
        mIvCheck.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                setChecked(true);
                setFinishCount();
            }
        });
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putParcelableArrayListExtra(LifeStoryActivity.KEY_SELECTED_IMAGE, (ArrayList<? extends Parcelable>) mImageList);
        setResult(RESULT_OK,intent);
        finish();
    }

    /**
     * 设置标题
     */
    private void setTitle(){
        String title = String.format(getString(R.string.xiegang),mCurrentIndex + 1,mTotalSize);
        mTvTtitle.setText(title);
    }

    /**
     * 设置 每个图片的选中图片
     * @param isClick
     */
    private void setChecked(boolean isClick){
        PreviewImage image = mImageList.get(mCurrentIndex);
        if(isClick){
            image.setChecked(image.isChecked() ? false : true);
        }
        mIvCheck.setSelected(image.isChecked());
    }

    /**
     * 设置选择多少图片
     */
    private void setFinishCount(){
        int count = 0;
        for (PreviewImage image : mImageList){
            if(image.isChecked()){
                count++;
            }
        }

        if(count == 0){
            mTvFinish.setText(getString(R.string.display_exit_edit));
        }else{
            String s = String.format(getString(R.string.finish_num),count);
            SpannableStringBuilder sb = new SpannableStringBuilder(s);
            sb.setSpan(new StyleSpan(Typeface.BOLD), s.indexOf(" "), sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            mTvFinish.setText(sb);
        }
    }

    /**
     * 图片设置点击事件
     */
    private void setOnTap(final int position){
        mVp.post(new Runnable() {
            @Override
            public void run() {
                View v = mVp.findViewById(position);
                if (v instanceof PhotoDraweeView) {
                    ((PhotoDraweeView) v).setOnViewTapListener(ImagePreviewActivity.this);
                }
            }
        });
    }



    private void onItemChange(int position) {
        PreviewImage image = mImagePreviewAdapter.getItem(position);
        mCurrentIndex = position;
        setTitle();
        setChecked(false);
    }

    public static void launch(Activity activity,ArrayList<PreviewImage> paths,int currentImageIndex,int requestCode){
        Intent intent  = new Intent(activity,ImagePreviewActivity.class);
        intent.putExtra(KEY_PATHS,paths);
        intent.putExtra(KEY_CURRENT_IMAGE_INDEX,currentImageIndex);
        activity.startActivityForResult(intent,requestCode);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            /**左上角图片点击时间*/
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        onItemChange(position);
        setOnTap(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onViewTap(View view, float x, float y) {
        if(mRlFooter.isShown()){
            mRlFooter.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bottom_out));
            mRlFooter.setVisibility(View.GONE);
        }else {
            mRlFooter.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bottom_in));
            mRlFooter.setVisibility(View.VISIBLE);
        }

        if(mAppBar.isShown()){
            mAppBar.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),R.anim.top_out));
            mAppBar.setVisibility(View.GONE);
        }else{
            mAppBar.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),R.anim.top_in));
            mAppBar.setVisibility(View.VISIBLE);
        }
    }
}
